package com.example.springboot.controller;

import com.example.springboot.entity.Goods;
import com.example.springboot.mapper.GoodsMapper;
import com.example.springboot.mapper.OrderMapper;
import com.example.springboot.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderMapper orderMapper;

    //用get请求查询数据库信息
    @GetMapping
    public List<Goods> findAll(){
        return goodsMapper.findAll();//查询所有数据
    }

    //用post请求对数据库数据进行增加和修改
    @PostMapping
    public Integer save(@RequestBody Goods goods){
        return goodsService.save(goods);//往数据库插入或更新数据
    }

    //批量增加
    @PostMapping("/save/batch")
    public Integer saveBatch(@RequestBody Goods goodsArray[]){

        Integer num = 0;
        Integer id = orderMapper.findLatest();
        for(int i=0; i< goodsArray.length;i++){
            Goods goods = goodsArray[i];
            goods.setOrderId(id);
            num = goodsService.save(goods);
        }
        return num;
    }

    @GetMapping("/order/{id}")
    public List<Goods> selectByOrderId(@PathVariable Integer id){

        return goodsMapper.selectByOrderId(id);//往数据库插入或更新数据
    }

}
